/**
 * 生成验证码
 * @param {HTMLCanvasElement} canvas - Canvas元素
 * @returns {string} 返回生成的验证码文本
 */
export const generateCaptcha = (canvas) => {
  const ctx = canvas.getContext('2d')
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  // 设置背景
  ctx.fillStyle = '#f3f3f3'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 生成随机验证码
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let code = ''
  for (let i = 0; i < 4; i++) {
    const char = chars[Math.floor(Math.random() * chars.length)]
    code += char
    
    // 随机颜色
    ctx.fillStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.font = 'bold 30px Arial'
    ctx.textBaseline = 'middle'
    
    // 随机旋转
    const x = 10 + i * 30
    const y = canvas.height / 2
    const angle = (Math.random() - 0.5) * 0.1
    ctx.translate(x, y)
    ctx.rotate(angle)
    ctx.fillText(char, 0, 0)
    ctx.rotate(-angle)
    ctx.translate(-x, -y)
  }
  
  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.lineWidth = 1
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
  
  // 添加干扰点
  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 0.8, 0, 2 * Math.PI)
    ctx.fill()
  }
  
  return code
}